<template>
  <div v-loading="pageLoading" :class="{'mobile-create': showMobilePage}" class="termination-create-container">
    <explanation :explanation="explanationObj" is-expand style="margin: 0;"/>
    <div class="page-container mobile-small-padding">
      <TerminationInfo ref="terminationInfoRef" v-model="detailData" :show-mobile-page="showMobilePage" style="margin-bottom: 32px;" />
      <LinkSignUp ref="linkSignUpRef" v-model="detailData" :show-mobile-page="showMobilePage"/>

      <ContractInfo
        ref="contractInfoRef"
        :data="detailData.linkContract"
        :show-mobile-page="showMobilePage"
        is-edit
        @handleDeleteContract="handleDeleteContract"
        @confirmRelatedContract="confirmRelatedContract" />
    </div>
    <fixed-pagination>
      <div class="center">
        <el-button size="small" type="primary" @click="openDrawer()">发起审批</el-button>
        <el-button v-if="(!remodifyId && !reapplyId)|| createNew" class="empty-btn-style" size="small" type="info" @click="submit(SUBMITTYPE.DRAFT)">保存草稿</el-button>
        <el-button class="cancel-btn-style" size="small" @click="toBack">返回</el-button>
      </div>
    </fixed-pagination>

    <AuditProcess
      ref="auditProcess"
      :loading="processLoading"
      v-model="auditInfo"
      :default-aduitor-list="[userInfo]"
      :old-audit-info="oldAuditInfo"
      :flow-structure="processDetail"
      :is-modify="Boolean(remodifyId)"
      :disable="Boolean(remodifyId)"
      :is-modify-form="Number(isModifyForm)"
      :current-process-index="Number(currentProcessIndex)"
      @submit="submit(SUBMITTYPE.SUBMIT,$event)"
      @getProcess="getProcess" />
  </div>
</template>

<script>
// COMPOENTS
import explanation from '@/components/Common/explanation';
import TerminationInfo from './components/createTerminationInfo';
import LinkSignUp from './components/createLinkSignUp';
import AuditProcess from '@/components/Common/auditProcess';
import ContractInfo from './detail/module/contractInfo';
// API
import { processManagementDetail } from '@/api/legal';
import { formSubmit, terminationCreate, terminationEdit, getTerminationDetail } from '@/api/termination';
// TOOL
import { mapState } from 'vuex';
import { SUBMITTYPE } from '@/utils/const/cost';
import { FIXED_PROCESS_TYPE } from '@/utils/const/process';
import { createAuditStructure } from '@/utils/aduitor';
import { isContained } from '@/utils/tools';
import ElMessage from '@/utils/message';
import { showModal } from '@/utils/message';
// MIXINS
import mobileCreate from '@/mixins/mobileCreate';
import processCreate from '@/mixins/processCreate';

export default {
  components: { explanation, TerminationInfo, LinkSignUp, AuditProcess, ContractInfo },
  mixins: [processCreate, mobileCreate],
  data() {
    return {
      SUBMITTYPE,
      pageLoading: false,
      id: '',
      isEdit: false,
      detailData: {
        createUser: '',
        departmentId: '',
        terminationExplain: '',
        terminationTime: '',
        explain: '',
        attachment: [],
        linkSignUp: {
          id: '',
          accountsInfoList: []
        },
        linkContract: []
      },
      // 流程相关数据
      processDetail: null,
      remodifyId: null, // 修改，审批流程不能修改
      reapplyId: null, // 重新申请
      explanationObj: {
        content: '',
        styConfig: ''
      }, // 审批说明
      processLoading: false,
      auditInfo: {
        activeTime: null,
        isSigner: 0,
        countersignSet: 0,
        process: [],
        senders: [],
        id: null
      }, // 流程信息
      oldAuditInfo: null // 保存旧流程用于比较，修改的情况需要判断流程是否发生变动
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    processStructure() {
      if (!this.processDetail) return [];
      return this.processDetail.process || [];
    }
  },
  created() {
    this.createNew = Number(this.$route.query.createNew) || 0;// 再次发起（复制）
    const id = this.$route.params.id;
    this.remodifyId = this.$route.query.remodifyId; // 修改
    this.reapplyId = this.$route.query.reapplyId; // 重新申请
    if (id) {
      this.id = id;
      this.isEdit = true;
      this.getData();
      this.reapplyId && this.getExplanation();
    } else {
      this.detailData.createUserId = this.userInfo.id;
      this.detailData.createUser = this.userInfo.userName;
      if (this.userInfo.deptName && this.userInfo.deptName.length) {
        this.detailData.departmentId = this.getFirstDepartment(this.userInfo.departmentAry);
      }
      this.isEdit = false;
      this.getExplanation();
    }
  },
  methods: {
    // 获取用户第一个部门的第一个子级部门
    getFirstDepartment(list) {
      if (Array.isArray(list) && list.length) {
        const deptIdArr = list[0].id;
        if (Array.isArray(deptIdArr) && deptIdArr.length) {
          return deptIdArr[deptIdArr.length - 1];
        } else {
          return null;
        }
      }
      return null;
    },
    submit(submitType = SUBMITTYPE.SUBMIT, senders = []) { // 1草稿 2保存提交 3重新提交
      this.modifySenders = senders;// 存到mixins
      const params = JSON.parse(JSON.stringify(this.detailData));
      if (params.linkSignUp.accountsInfoList && params.linkSignUp.accountsInfoList.length) {
        params.linkSignUp.accountsInfoList = params.linkSignUp.accountsInfoList.filter(i => !!i.id);
      }
      params.submitType = submitType;
      params.isEditAudit = false;
      if (this.remodifyId && this.isRefresh) {
        params.isEditAudit = true;// 修改时，流程被编辑或者更新
      }
      params.auditInfo = this.auditInfo;
      if (this.createNew) {
        delete params.id;
      }
      if (this.isModifyForm) { // 节点修改走编辑的逻辑
        this.handleModifyData(params);
        this.edit(params);
        return;
      }
      showModal(submitType === SUBMITTYPE.DRAFT ? '请确认是否保存草稿' : '请确认是否发起审批', '', {
        confirmButtonText: '确定', type: 'warning', showClose: false,
        center: true, iconClass: 'charge-icon', customClass: 'del-message del-message-cancel'
      }).then(() => {
        if (this.reapplyId || !this.isEdit) {
          this.add(params);
        } else {
          this.handleModifyData(params);
          this.edit(params);
        }
      });
      // 重新申请或者新建
    },
    add(params) {
      if (this.reapplyId && !this.createNew) params.submitType = 3;
      terminationCreate(params).then(res => {
        this.httpCallBack(res, params);
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcess'].setShowRefresh(true);
        }
        this.loading = false;
      });
    },
    edit(params) {
      params.id = this.id;
      terminationEdit(params).then(res => {
        this.httpCallBack(res, params);
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcess'].setShowRefresh(true);
        }
        if (err.code === 505) { // 节点修改跳转详情
          this.nodeModifyJumpDetail({ routeName: 'terminationDetail', params: {}, query: { terminationId: this.id, processId: this.remodifyId }});
        }
        this.loading = false;
      });
    },
    httpCallBack(res, params) {
      if (res.code === 200) {
        ElMessage.success(params.submitType === SUBMITTYPE.DRAFT ? '保存成功' : '发起成功');
        if (res.data.processId) {
          this.$router.push({
            name: 'terminationDetail',
            query: { terminationId: res.data.id || params.id, processId: res.data.processId }
          });
        } else {
          this.toBack();
        }
      } else {
        ElMessage.error(res.message);
      }
    },
    getData() {
      getTerminationDetail(this.id).then(res => {
        if (res.data) {
          if (res.data.linkContract && res.data.linkContract.length) {
            res.data.linkContract.forEach(i => {
              if (!i.proposerDepartmentName) i.proposerDepartmentName = i.proposerDepartment;
            });
          }
          if (res.data.terminationTime && res.data.terminationTime.toString().length === 10) {
            res.data.terminationTime = res.data.terminationTime * 1000;
          }
          if (res.data.auditInfo && !this.reapplyId) {
            this.oldAuditInfo = Object.assign({}, res.data.auditInfo);
            this.auditInfo = JSON.parse(JSON.stringify(res.data.auditInfo));
            this.processDetail = JSON.parse(JSON.stringify(res.data.auditInfo));
          }
          delete res.data.auditInfo;
          this.detailData = res.data;
          if (this.createNew) {
            this.detailData.createUserId = this.userInfo.id;
            this.detailData.createUser = this.userInfo.userName;
          }
          // status 0：草稿中
          if (res.data.isDraft || !this.auditInfo || !this.auditInfo.id || this.reapplyId) {
            this.getExplanation();
          }
          this.version = Number(res.data.version) || 0;// 当前详情版本，version存在mixins
        }
      });
    },
    toBack() {
      this.$router.push({
        name: 'termination'
      });
    },
    confirmRelatedContract(data) {
      let res = [];
      res = data.map(i => {
        return {
          id: i.id,
          contractCode: i.contractCode,
          contractName: i.contractName,
          contractType: i.contractType,
          processId: i.processId,
          proposer: i.proposer,
          proposerDepartment: i.proposerDepartmentName || i.department,
          department: i.department,
          proposerId: i.proposerId,
          creator: i.creator,
          creatorId: i.creatorId
        };
      });
      this.detailData.linkContract = res;
    },
    handleDeleteContract(contractId) {
      this.detailData.linkContract = this.detailData.linkContract.filter(i => i.id !== contractId);
    },
    /**
     * 流程
     */
    openDrawer() { // 2.9.7 流程弹窗
      const promise = [];
      promise.push(this.$refs.terminationInfoRef.validateForm());
      promise.push(this.$refs.linkSignUpRef.validateForm());
      Promise.all(promise).then(res => { // 表单校验通过，则仅提交供应商表单部分，不提交流程信息，用来获取最新流程
        this.getProcessDetail();
        // 重新申请或者新建
      }).catch((errMsg) => {
        ElMessage.warning(errMsg || '请检查信息是否填写完整');
      });
    },
    getProcess() {
      this.getProcessDetail(true);
      this.isRefresh = true;
    },
    isProcessChange(nowAuditInfo = {}, oldAuditInfo = {}) {
      if (nowAuditInfo.activationTime !== (oldAuditInfo.activeTime / 1000)) {
        return true;
      }
      const nowProcessIds = nowAuditInfo && nowAuditInfo.process.map(el => el.id) || [];
      const oldProcessIds = oldAuditInfo && oldAuditInfo.process.map(el => el.templateNodeId) || [];
      if (!isContained(nowProcessIds, oldProcessIds)) {
        return true;
      }
      return false;
    },
    // 获取流程详情
    getProcessDetail(isRefresh = false) {
      this.loading = true;
      const params = JSON.parse(JSON.stringify(this.detailData));
      if (params.linkSignUp.accountsInfoList && params.linkSignUp.accountsInfoList.length) {
        params.linkSignUp.accountsInfoList = params.linkSignUp.accountsInfoList.filter(i => !!i.id);
      }
      params.type = FIXED_PROCESS_TYPE.TERMINATION;
      formSubmit(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          const data = res.data;
          if (this.remodifyId && !isRefresh) {
            this.isProcessChange(data, this.oldAuditInfo) && this.$refs['auditProcess'].setShowRefresh(true);
          } else {
            this.processDetail = data;
            this.auditInfo.activeTime = data.activationTime;
            this.auditInfo.id = data.id;
            // 创建人回填
            this.auditInfo.process = createAuditStructure(data.process, this.userInfo, this.userInfo);
            this.auditInfo.senders = data.senderDiyUserList || [];
          }
          if (this.remodifyId && isRefresh) { // 修改刷新保存刷新后流程用于对比
            this.oldAuditInfo = Object.assign({}, data);
            this.oldAuditInfo.process.forEach(el => {
              this.oldAuditInfo.templateNodeId = el.id;
            });
            this.oldAuditInfo.activeTime = data.activationTime * 1000;
          }
          this.$refs['auditProcess'].openDrawer();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.loading = false;
        console.log(err);
      });
    },
    getExplanation() { // 获取审批说明
      processManagementDetail({ id: 3527, type: FIXED_PROCESS_TYPE.TERMINATION }).then(res => {
        // 审批说明
        const data = res.data[0];
        this.explanationObj.content = data.explanation || '';
        this.explanationObj.styConfig = data.styConfig || '';
      }).catch(err => {
        console.log(err);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.termination-create-container {
  margin: 16px;
  background-color: #fff;
  min-height: calc(100vh - 80px);
}
.page-container {
  padding: 24px;
  padding-bottom: 55px;
}
.empty-btn-style {
  border-color: #406EFF;
  background: #fff;
  color: #406EFF;
  width: 80px;
  padding: 7px 0;
  text-align: center;
}
</style>
